//@version=6
indicator("Smart Algo Signals Suite [AlgoChief]", overlay = true, max_lines_count = 500, max_boxes_count = 500, max_labels_count = 500)

// ============================================================================
// 1. INPUT CONFIGURATION & DASHBOARD CONTROLS
// ============================================================================

// --- Master Component Dashboard ---
grp_master = "⚙️ Master Dashboard - Component Toggles"
show_signals    = input.bool(true,  "Enable Smart Signals Engine",                group = grp_master)
show_fvt        = input.bool(true,  "Enable Fair Value Trail (FVT v2)",           group = grp_master)
show_spine      = input.bool(false, "Enable Trend Spine",                         group = grp_master)
show_bias       = input.bool(false, "Enable Trend Bias Band",                     group = grp_master)
show_clouds     = input.bool(false, "Enable Firmament Volatility Clouds",         group = grp_master)
show_trc        = input.bool(true,  "Enable Trend-Range Classifier (TRC)",        group = grp_master)
show_tpsl       = input.bool(true,  "Enable Automated Trade Management (TP/SL)",  group = grp_master)
show_dashboard  = input.bool(true,  "Enable Component Status Table",              group = grp_master)

// --- Smart Signals Engine ---
grp_signals = "🧠 Smart Signals Engine"
engine_mode        = input.string("Swing", "Engine Mode", options = ["Swing", "Scalping"], group = grp_signals)
signal_mode        = input.string("Trend", "Signal Type", options = ["Trend", "Reversal"], group = grp_signals)
time_horizon       = input.string("Medium Term", "Time Horizon", options = ["Short Term", "Medium Term", "Long Term"], group = grp_signals)
filter_sens        = input.float(1.3, "Sensitivity Multiplier", minval = 0.2, maxval = 5.0, step = 0.1, group = grp_signals)
enable_strong      = input.bool(true, "Distinguish Strong Signals (+▲ / +▼)", group = grp_signals)
vol_surge_mult     = input.float(1.25, "Strong Signal Volume Multiplier", minval = 1.0, step = 0.05, group = grp_signals)
show_opt_entries   = input.bool(true, "Show Optimal Entry Signals (FVT Retests)", group = grp_signals)
show_exit_marks    = input.bool(true, "Show Momentum Exit Markers (✕)", group = grp_signals)

// --- Fair Value Trail (FVT v2) ---
grp_fvt = "🌊 Fair Value Trail (FVT v2)"
fvt_period       = input.int(55, "FVT Volume Lookback", minval = 10, group = grp_fvt)
fvt_width_factor = input.float(1.15, "FVT Band Width Multiplier", minval = 0.2, step = 0.05, group = grp_fvt)

// --- Trend Spine ---
grp_spine = "🦴 Trend Spine"
spine_length     = input.int(50, "Spine Lookback Period", minval = 10, group = grp_spine)
spine_thresh     = input.float(0.45, "Spine Noise Filter Threshold", minval = 0.1, step = 0.05, group = grp_spine)

// --- Trend Bias ---
grp_bias = "⚡ Trend Bias"
bias_length      = input.int(80, "Bias Base Period", minval = 10, group = grp_bias)
bias_smooth      = input.int(12, "Momentum Smoothing Lookback", minval = 2, group = grp_bias)

// --- Firmament Clouds ---
grp_clouds = "☁️ Firmament Clouds"
clouds_baseline  = input.int(100, "Clouds Baseline Period", minval = 20, group = grp_clouds)
clouds_inner     = input.float(2.0, "Inner Band Multiplier", minval = 0.5, step = 0.1, group = grp_clouds)
clouds_outer     = input.float(3.2, "Outer Band Multiplier", minval = 1.0, step = 0.1, group = grp_clouds)
clouds_highlight = input.bool(true, "Highlight Overextended Reversal Bars", group = grp_clouds)

// --- Trend-Range Classifier (TRC) ---
grp_trc = "🤖 Trend-Range Classifier (TRC)"
trc_lookback     = input.int(24, "TRC Multi-Feature Lookback", minval = 10, group = grp_trc)
trc_threshold    = input.float(48.0, "Trend Classification Threshold", minval = 30.0, maxval = 70.0, step = 1.0, group = grp_trc)
trc_gray_candles = input.bool(true, "Highlight Ranging Candles with Neutral Slate Gray", group = grp_trc)
trc_bg_shading   = input.bool(false, "Highlight Trending Regime in Background", group = grp_trc)

// --- Candle Coloring ---
grp_candles = "🎨 Candle Coloring"
candle_coloring  = input.string("Trend Gradient", "Coloring Mode", options = ["None", "Static Trend", "Trend Gradient", "Volume Gradient"], group = grp_candles)

// --- Dynamic TP / SL Trade Management ---
grp_tpsl = "🎯 Automated Trade Management (TP/SL)"
tpsl_calc_mode   = input.string("Volatility (ATR)", "Target Calculation Basis", options = ["Volatility (ATR)", "Percentage"], group = grp_tpsl)
tp_targets_count = input.int(3, "Number of Take-Profit Targets", minval = 1, maxval = 3, group = grp_tpsl)
sl_factor        = input.float(1.5, "Stop-Loss Multiplier / %", minval = 0.2, step = 0.1, group = grp_tpsl)
tp1_factor       = input.float(1.0, "TP 1 Multiplier / %", minval = 0.2, step = 0.1, group = grp_tpsl)
tp2_factor       = input.float(2.0, "TP 2 Multiplier / %", minval = 0.4, step = 0.1, group = grp_tpsl)
tp3_factor       = input.float(3.0, "TP 3 Multiplier / %", minval = 0.6, step = 0.1, group = grp_tpsl)
render_rr_boxes  = input.bool(true, "Render Visual Risk/Reward Projection Zones", group = grp_tpsl)

// --- Component Status Dashboard Table ---
grp_table = "📋 Component Status Dashboard"
table_position_in = input.string("Top Right", "Table Placement", options = ["Top Right", "Bottom Right", "Bottom Left", "Top Left"], group = grp_table)
table_size_in     = input.string("Small", "Table Sizing", options = ["Tiny", "Small", "Normal", "Large"], group = grp_table)

// --- Multi-Step Confluence Alerts ---
grp_alerts = "🔔 Multi-Step Confluence Alert Builder"
alert_trigger_filter = input.string("All Signals", "Primary Alert Trigger", options = ["All Signals", "Strong Signals Only", "Normal Signals Only", "Optimal Entries Only", "Exit Signals Only"], group = grp_alerts)
alert_req_trc        = input.bool(false, "Step 2 Confluence: Require Market Is Trending (TRC)", group = grp_alerts)
alert_req_fvt        = input.bool(false, "Step 3 Confluence: Require FVT Trend Agreement", group = grp_alerts)
alert_req_spine      = input.bool(false, "Step 4 Confluence: Require Trend Spine Agreement", group = grp_alerts)
alert_req_bias       = input.bool(false, "Step 5 Confluence: Require Trend Bias Agreement", group = grp_alerts)

// ============================================================================
// 2. LUXURY INSTITUTIONAL COLOR PALETTE (ALGOALPHA PAID-SPACE STANDARD)
// ============================================================================

// Bullish Signature: Cyan Neon / Deep Emerald Glow
color C_NEON_CYAN     = #00f0ff
color C_AQUA_MINT     = #00d2b4
color C_TEAL_PRIMARY  = #00897b
color C_TEAL_DARK     = #004d40
color C_BULL_CLOUD_BG = color.new(#00b4d8, 86)
color C_BULL_BORDER   = color.new(#00e5ff, 40)

// Bearish Signature: Crimson Neon / Rose Wine Glow
color C_NEON_CRIMSON  = #ff1744
color C_CORAL_VIBRANT = #ff3366
color C_RED_PRIMARY   = #c92a2a
color C_WINE_DARK     = #7a0018
color C_BEAR_CLOUD_BG = color.new(#d90429, 86)
color C_BEAR_BORDER   = color.new(#ff1744, 40)

// Accents & Neutrals
color C_AMBER_GOLD    = #ffb703
color C_SLATE_GRAY    = #64748b
color C_DARK_CHARCOAL = #1e222d
color C_TABLE_BG      = #131722
color C_WHITE_CLEAN   = #f8fafc

// ============================================================================
// 3. CORE ENGINES & MATHEMATICAL COMPUTATION
// ============================================================================

// Base period mapped to Time Horizon
int base_horizon_len = time_horizon == "Short Term" ? 60 : time_horizon == "Medium Term" ? 120 : 200
float atr_core = ta.atr(14)
float vol_ma20 = ta.sma(volume, 20)

// --- F. Trend-Range Classifier (TRC) ---
float trc_atr_sum = math.sum(ta.tr, trc_lookback)
float trc_high_low_span = ta.highest(high, trc_lookback) - ta.lowest(low, trc_lookback)
float trc_chop = trc_high_low_span > 0 ? 100.0 * (math.log10(trc_atr_sum / trc_high_low_span) / math.log10(trc_lookback)) : 50.0

float trc_dist_net = math.abs(close - close[trc_lookback])
float trc_dist_sum = math.sum(math.abs(close - close[1]), trc_lookback)
float trc_er = trc_dist_sum > 0 ? (trc_dist_net / trc_dist_sum) : 0.0

[di_p, di_m, trc_adx_val] = ta.dmi(14, 14)
float trc_trend_score = ((100.0 - trc_chop) * 0.40) + ((trc_er * 100.0) * 0.35) + (trc_adx_val * 0.25)
bool trc_is_trending = trc_trend_score >= trc_threshold
int trc_state = trc_is_trending ? (close >= ta.ema(close, trc_lookback) ? 1 : -1) : 0

// Background Shading for TRC Trending Regime
bgcolor(trc_bg_shading and show_trc ? (trc_is_trending ? color.new(color.blue, 94) : na) : na)

// --- A. Smart Signals Engine (Swing vs Scalping) ---
// 1. Swing Engine: Adaptive Price Stability & Hysteresis Envelope Filter
float net_change = math.abs(close - close[base_horizon_len])
float sum_change = math.max(ta.sma(math.abs(close - close[1]), base_horizon_len) * base_horizon_len, 0.00001)
float efficiency_ratio = net_change / sum_change
float stability_speed = math.pow(efficiency_ratio * (2.0 / 3.0 - 2.0 / (base_horizon_len + 1.0)) + 2.0 / (base_horizon_len + 1.0), 2) * filter_sens
float alpha_swing = math.max(0.005, math.min(0.35, stability_speed))

var float swing_baseline = close
swing_baseline := nz(swing_baseline[1], close) + alpha_swing * (close - nz(swing_baseline[1], close))

// Volatility Hysteresis Band: Prevents false micro-whipsaws
float swing_threshold = atr_core * (0.80 / math.max(filter_sens, 0.4))
var int swing_state = 0
if close > swing_baseline + swing_threshold
    swing_state := 1
else if close < swing_baseline - swing_threshold
    swing_state := -1

// 2. Scalping Engine: Dynamic Multi-Regime Fast Momentum Classifier
int scalp_fast_p = time_horizon == "Short Term" ? 7 : time_horizon == "Medium Term" ? 10 : 14
int scalp_slow_p = time_horizon == "Short Term" ? 16 : time_horizon == "Medium Term" ? 24 : 32
float scalp_ema_f = ta.ema(close, scalp_fast_p)
float scalp_ema_s = ta.ema(close, scalp_slow_p)
float scalp_rsi   = ta.rsi(close, 14)

var int scalp_state = 0
if scalp_ema_f > scalp_ema_s and scalp_rsi > 50
    scalp_state := 1
else if scalp_ema_f < scalp_ema_s and scalp_rsi < 50
    scalp_state := -1

// Active Engine Direction
int core_engine_dir = engine_mode == "Swing" ? swing_state : scalp_state

// Signal Triggers: Direct & Responsive (Never Blocked by Ranging Filter)
bool raw_bull_signal = false
bool raw_bear_signal = false

if signal_mode == "Trend"
    raw_bull_signal := (core_engine_dir == 1 and core_engine_dir[1] != 1)
    raw_bear_signal := (core_engine_dir == -1 and core_engine_dir[1] != -1)
else
    // Reversal Mode: Detects price exhaustion outside standard deviations with price action confirmation
    float rev_basis = ta.sma(close, 20)
    float rev_dev   = 2.1 * ta.stdev(close, 20)
    float rev_rsi   = ta.rsi(close, 9)
    bool bull_exhaustion = (low <= rev_basis - rev_dev or rev_rsi < 30) and close > open and close > high[1]
    bool bear_exhaustion = (high >= rev_basis + rev_dev or rev_rsi > 70) and close < open and close < low[1]
    raw_bull_signal := bull_exhaustion and ta.change(bull_exhaustion)
    raw_bear_signal := bear_exhaustion and ta.change(bear_exhaustion)

// Conviction Classification: Normal vs Strong (+▲ / +▼)
bool vol_expansion = volume >= vol_ma20 * vol_surge_mult
bool bull_conviction = vol_expansion and ta.rsi(close, 14) > 54 and close > ta.ema(close, 50)
bool bear_conviction = vol_expansion and ta.rsi(close, 14) < 46 and close < ta.ema(close, 50)

bool is_strong_bull = raw_bull_signal and bull_conviction and enable_strong
bool is_normal_bull = raw_bull_signal and not is_strong_bull

bool is_strong_bear = raw_bear_signal and bear_conviction and enable_strong
bool is_normal_bear = raw_bear_signal and not is_strong_bear

// --- B. Fair Value Trail (FVT v2) ---
// Volume-weighted dynamic fair value tracking with volatility envelope
float fvt_vwma = ta.vwma(hlc3, fvt_period)
float fvt_band_width = ta.atr(fvt_period) * fvt_width_factor

var int fvt_dir = 1
var float fvt_upper_band = na
var float fvt_lower_band = na

if fvt_dir == 1
    float cur_top = fvt_vwma
    float cur_bot = fvt_vwma - fvt_band_width
    fvt_lower_band := na(fvt_lower_band[1]) ? cur_bot : math.max(nz(fvt_lower_band[1]), cur_bot)
    fvt_upper_band := fvt_lower_band + fvt_band_width
    if close < fvt_lower_band
        fvt_dir := -1
        fvt_upper_band := fvt_vwma + fvt_band_width
        fvt_lower_band := fvt_upper_band - fvt_band_width
else
    float cur_bot = fvt_vwma
    float cur_top = fvt_vwma + fvt_band_width
    fvt_upper_band := na(fvt_upper_band[1]) ? cur_top : math.min(nz(fvt_upper_band[1]), cur_top)
    fvt_lower_band := fvt_upper_band - fvt_band_width
    if close > fvt_upper_band
        fvt_dir := 1
        fvt_lower_band := fvt_vwma - fvt_band_width
        fvt_upper_band := fvt_lower_band + fvt_band_width

// Optimal Entry Retest Signals (Pullback touches Fair Value Trail)
bool opt_entry_bull = fvt_dir == 1 and low <= fvt_upper_band and low >= fvt_lower_band - (fvt_band_width * 0.20) and close > open and not raw_bull_signal
bool opt_entry_bear = fvt_dir == -1 and high >= fvt_lower_band and high <= fvt_upper_band + (fvt_band_width * 0.20) and close < open and not raw_bear_signal

// Prevent clutter: Cooldown between optimal entry signals
var int last_opt_bull_bar = -50
var int last_opt_bear_bar = -50
bool fire_opt_bull = false
bool fire_opt_bear = false

if opt_entry_bull and (bar_index - last_opt_bull_bar > 4)
    fire_opt_bull := true
    last_opt_bull_bar := bar_index

if opt_entry_bear and (bar_index - last_opt_bear_bar > 4)
    fire_opt_bear := true
    last_opt_bear_bar := bar_index

// --- C. Trend Spine ---
// Stepped noise filter that ignores micro-oscillations during low directional momentum
float spine_raw_ma = ta.ema(hl2, spine_length)
float spine_atr_v  = ta.atr(spine_length)
float spine_delta  = math.abs(spine_raw_ma - nz(spine_raw_ma[3]))

var float spine_level = spine_raw_ma
if spine_delta > spine_atr_v * spine_thresh
    spine_level := spine_raw_ma

int spine_dir = close >= spine_level ? 1 : -1

// --- D. Trend Bias ---
// Momentum acceleration vs deceleration band
float bias_baseline = ta.wma(close, bias_length)
float bias_momentum = ta.mom(bias_baseline, bias_smooth)
float bias_mom_hist = ta.sma(math.abs(bias_momentum), 25)

int bias_dir = bias_momentum >= 0 ? 1 : -1
bool bias_accelerating = bias_dir == 1 ? (bias_momentum > bias_momentum[1] and bias_momentum > bias_mom_hist) : (bias_momentum < bias_momentum[1] and math.abs(bias_momentum) > bias_mom_hist)

color bias_color = bias_dir == 1 ? (bias_accelerating ? C_NEON_CYAN : C_TEAL_PRIMARY) : (bias_accelerating ? C_NEON_CRIMSON : C_RED_PRIMARY)

// --- E. Firmament Volatility Clouds ---
// Dynamic adaptive volatility boundaries
float c_mid_line = ta.sma(close, clouds_baseline)
float c_atr_val  = ta.atr(clouds_baseline)
float c_res_outer = c_mid_line + clouds_outer * c_atr_val
float c_res_inner = c_mid_line + clouds_inner * c_atr_val
float c_sup_inner = c_mid_line - clouds_inner * c_atr_val
float c_sup_outer = c_mid_line - clouds_outer * c_atr_val

bool cloud_overbought = high >= c_res_inner
bool cloud_oversold   = low <= c_sup_inner
int cloud_status = cloud_overbought ? -1 : cloud_oversold ? 1 : 0

// --- G. Momentum Exit Signals (✕) ---
var int last_trade_dir = 0
if raw_bull_signal
    last_trade_dir := 1
else if raw_bear_signal
    last_trade_dir := -1

var int last_exit_bar = -50
bool exit_long  = last_trade_dir == 1 and (ta.crossunder(ta.rsi(close, 14), 68) or (high == ta.highest(high, 14) and close < open and high - close > (close - low) * 1.5))
bool exit_short = last_trade_dir == -1 and (ta.crossover(ta.rsi(close, 14), 32) or (low == ta.lowest(low, 14) and close > open and close - low > (high - close) * 1.5))

bool fire_exit = (exit_long or exit_short) and (bar_index - last_exit_bar > 6)
if fire_exit
    last_exit_bar := bar_index
    last_trade_dir := 0

// ============================================================================
// 4. CHART VISUALIZATION & PLOTTING (PREMIUM NEON AESTHETICS)
// ============================================================================

// --- Fair Value Trail Plots (display = display.pane prevents status line pollution) ---
p_fvt_up = plot(show_fvt ? fvt_upper_band : na, "FVT Upper Boundary", color = fvt_dir == 1 ? C_BULL_BORDER : C_BEAR_BORDER, linewidth = 1, display = display.pane)
p_fvt_dn = plot(show_fvt ? fvt_lower_band : na, "FVT Lower Boundary", color = fvt_dir == 1 ? C_BULL_BORDER : C_BEAR_BORDER, linewidth = 1, display = display.pane)
fill(p_fvt_up, p_fvt_dn, color = show_fvt ? (fvt_dir == 1 ? C_BULL_CLOUD_BG : C_BEAR_CLOUD_BG) : na, title = "FVT Glowing Cloud Fill")

// --- Trend Spine Plot ---
plot(show_spine ? spine_level : na, "Trend Spine Backbone", color = spine_dir == 1 ? C_AQUA_MINT : C_CORAL_VIBRANT, linewidth = 2, style = plot.style_linebr, display = display.pane)

// --- Trend Bias Plot ---
plot(show_bias ? bias_baseline : na, "Trend Bias Momentum Band", color = bias_color, linewidth = 3, display = display.pane)

// --- Firmament Clouds Plots ---
p_c_res_out = plot(show_clouds ? c_res_outer : na, "Firmament Resistance Outer", color = color.new(C_NEON_CRIMSON, 55), linewidth = 1, display = display.pane)
p_c_res_inn = plot(show_clouds ? c_res_inner : na, "Firmament Resistance Inner", color = color.new(C_NEON_CRIMSON, 55), linewidth = 1, display = display.pane)
fill(p_c_res_out, p_c_res_inn, color = show_clouds ? color.new(C_NEON_CRIMSON, 88) : na, title = "Firmament Resistance Cloud")

p_c_sup_inn = plot(show_clouds ? c_sup_inner : na, "Firmament Support Inner", color = color.new(C_NEON_CYAN, 55), linewidth = 1, display = display.pane)
p_c_sup_out = plot(show_clouds ? c_sup_outer : na, "Firmament Support Outer", color = color.new(C_NEON_CYAN, 55), linewidth = 1, display = display.pane)
fill(p_c_sup_inn, p_c_sup_out, color = show_clouds ? color.new(C_NEON_CYAN, 88) : na, title = "Firmament Support Cloud")

// --- Optimal Entry Signals (Micro Dots near Trail) ---
plotshape(show_fvt and show_opt_entries and fire_opt_bull, "Optimal Retest Buy Entry", style = shape.circle, location = location.belowbar, color = C_AQUA_MINT, size = size.tiny, display = display.pane)
plotshape(show_fvt and show_opt_entries and fire_opt_bear, "Optimal Retest Sell Entry", style = shape.circle, location = location.abovebar, color = C_CORAL_VIBRANT, size = size.tiny, display = display.pane)

// --- Momentum Exit Markers ---
plotchar(show_signals and show_exit_marks and fire_exit and exit_long,  "Momentum Exit Long Target",  char = "✕", location = location.abovebar, color = C_AMBER_GOLD, size = size.tiny, display = display.pane)
plotchar(show_signals and show_exit_marks and fire_exit and exit_short, "Momentum Exit Short Target", char = "✕", location = location.belowbar, color = C_AMBER_GOLD, size = size.tiny, display = display.pane)

// --- Smart Signals Plot Shapes / Sleek Pill Badges ---
plotshape(show_signals and is_normal_bull, "Normal Bullish Signal", style = shape.labelup, location = location.belowbar, color = #00897b, text = "▲", textcolor = C_WHITE_CLEAN, size = size.tiny, display = display.pane)
plotshape(show_signals and is_strong_bull, "Strong Bullish Signal", style = shape.labelup, location = location.belowbar, color = #00b4d8, text = "+▲", textcolor = C_WHITE_CLEAN, size = size.small, display = display.pane)

plotshape(show_signals and is_normal_bear, "Normal Bearish Signal", style = shape.labeldown, location = location.abovebar, color = #b71c1c, text = "▼", textcolor = C_WHITE_CLEAN, size = size.tiny, display = display.pane)
plotshape(show_signals and is_strong_bear, "Strong Bearish Signal", style = shape.labeldown, location = location.abovebar, color = #d90429, text = "+▼", textcolor = C_WHITE_CLEAN, size = size.small, display = display.pane)

// ============================================================================
// 5. ADVANCED CANDLE COLORING (ALGOALPHA DARK NEON THEME)
// ============================================================================

float mom_norm = math.max(0.0, math.min(1.0, (ta.rsi(close, 14) - 30.0) / 40.0))
color col_gradient_trend = core_engine_dir == 1 ? color.from_gradient(mom_norm, 0.0, 1.0, #0077b6, C_NEON_CYAN) : color.from_gradient(1.0 - mom_norm, 0.0, 1.0, #990024, C_CORAL_VIBRANT)

float vol_ratio = math.max(0.0, math.min(2.0, volume / math.max(vol_ma20, 1.0)))
color col_gradient_vol = close >= open ? color.from_gradient(vol_ratio, 0.5, 2.0, #005f73, C_NEON_CYAN) : color.from_gradient(vol_ratio, 0.5, 2.0, #6b001d, C_NEON_CRIMSON)

color dynamic_candle_col = na
if show_clouds and clouds_highlight and cloud_overbought
    dynamic_candle_col := #ff3366
else if show_clouds and clouds_highlight and cloud_oversold
    dynamic_candle_col := #00f0ff
else if show_trc and trc_gray_candles and not trc_is_trending
    dynamic_candle_col := C_SLATE_GRAY
else if candle_coloring == "Static Trend"
    dynamic_candle_col := core_engine_dir == 1 ? C_AQUA_MINT : C_CORAL_VIBRANT
else if candle_coloring == "Trend Gradient"
    dynamic_candle_col := col_gradient_trend
else if candle_coloring == "Volume Gradient"
    dynamic_candle_col := col_gradient_vol

barcolor(candle_coloring != "None" or (show_clouds and clouds_highlight and (cloud_overbought or cloud_oversold)) ? dynamic_candle_col : na)

// ============================================================================
// 6. AUTOMATED TRADE MANAGEMENT (ALWAYS LOCKS TO LATEST ACTIVE SIGNAL)
// ============================================================================

// Drawing storage objects
var line line_entry = na
var line line_sl    = na
var line line_tp1   = na
var line line_tp2   = na
var line line_tp3   = na

var label lbl_entry = na
var label lbl_sl    = na
var label lbl_tp1   = na
var label lbl_tp2   = na
var label lbl_tp3   = na

var box box_profit  = na
var box box_risk    = na

// Dynamic Level Variables (Exported for alerts and data window)
var float cur_entry_price = na
var float cur_sl_price    = na
var float cur_tp1_price   = na
var float cur_tp2_price   = na
var float cur_tp3_price   = na

var int active_trade_dir  = 0
var int active_start_bar  = 0
var bool trade_closed     = false

if show_tpsl and (raw_bull_signal or raw_bear_signal)
    // Clear previous drawings so only latest active trade exists on chart
    line.delete(line_entry)
    line.delete(line_sl)
    line.delete(line_tp1)
    line.delete(line_tp2)
    line.delete(line_tp3)

    label.delete(lbl_entry)
    label.delete(lbl_sl)
    label.delete(lbl_tp1)
    label.delete(lbl_tp2)
    label.delete(lbl_tp3)

    box.delete(box_profit)
    box.delete(box_risk)

    bool is_buy = raw_bull_signal
    active_trade_dir := is_buy ? 1 : -1
    active_start_bar := bar_index
    cur_entry_price  := close
    trade_closed     := false

    // Calculate Dynamic Risk / Reward Distances
    float dist_sl  = 0.0
    float dist_tp1 = 0.0
    float dist_tp2 = 0.0
    float dist_tp3 = 0.0

    if tpsl_calc_mode == "Volatility (ATR)"
        dist_sl  := atr_core * sl_factor
        dist_tp1 := atr_core * tp1_factor
        dist_tp2 := atr_core * tp2_factor
        dist_tp3 := atr_core * tp3_factor
    else
        dist_sl  := cur_entry_price * (sl_factor / 100.0)
        dist_tp1 := cur_entry_price * (tp1_factor / 100.0)
        dist_tp2 := cur_entry_price * (tp2_factor / 100.0)
        dist_tp3 := cur_entry_price * (tp3_factor / 100.0)

    cur_sl_price  := is_buy ? (cur_entry_price - dist_sl)  : (cur_entry_price + dist_sl)
    cur_tp1_price := is_buy ? (cur_entry_price + dist_tp1) : (cur_entry_price - dist_tp1)
    cur_tp2_price := is_buy ? (cur_entry_price + dist_tp2) : (cur_entry_price - dist_tp2)
    cur_tp3_price := is_buy ? (cur_entry_price + dist_tp3) : (cur_entry_price - dist_tp3)

    int bar_end = bar_index + 16

    // Draw Entry Level
    line_entry := line.new(active_start_bar, cur_entry_price, bar_end, cur_entry_price, color = #94a3b8, width = 1, style = line.style_dashed)
    lbl_entry  := label.new(bar_end, cur_entry_price, text = "Entry • " + str.tostring(cur_entry_price, format.mintick), style = label.style_label_left, color = #1e293b, textcolor = C_WHITE_CLEAN, size = size.tiny)

    // Draw Stop Loss Level
    line_sl := line.new(active_start_bar, cur_sl_price, bar_end, cur_sl_price, color = C_CORAL_VIBRANT, width = 1, style = line.style_solid)
    lbl_sl  := label.new(bar_end, cur_sl_price, text = "✗ SL • " + str.tostring(cur_sl_price, format.mintick), style = label.style_label_left, color = #880e4f, textcolor = C_WHITE_CLEAN, size = size.tiny)

    // Draw Take Profit Levels
    if tp_targets_count >= 1
        line_tp1 := line.new(active_start_bar, cur_tp1_price, bar_end, cur_tp1_price, color = C_AQUA_MINT, width = 1, style = line.style_solid)
        lbl_tp1  := label.new(bar_end, cur_tp1_price, text = "✓ TP1 • " + str.tostring(cur_tp1_price, format.mintick), style = label.style_label_left, color = #004d40, textcolor = C_WHITE_CLEAN, size = size.tiny)

    if tp_targets_count >= 2
        line_tp2 := line.new(active_start_bar, cur_tp2_price, bar_end, cur_tp2_price, color = C_AQUA_MINT, width = 1, style = line.style_solid)
        lbl_tp2  := label.new(bar_end, cur_tp2_price, text = "✓ TP2 • " + str.tostring(cur_tp2_price, format.mintick), style = label.style_label_left, color = #004d40, textcolor = C_WHITE_CLEAN, size = size.tiny)

    if tp_targets_count >= 3
        line_tp3 := line.new(active_start_bar, cur_tp3_price, bar_end, cur_tp3_price, color = C_AQUA_MINT, width = 1, style = line.style_solid)
        lbl_tp3  := label.new(bar_end, cur_tp3_price, text = "✓ TP3 • " + str.tostring(cur_tp3_price, format.mintick), style = label.style_label_left, color = #004d40, textcolor = C_WHITE_CLEAN, size = size.tiny)

    // Draw Visual Risk / Reward Zones with safe top >= bottom coordinates
    if render_rr_boxes
        float max_tp = tp_targets_count == 3 ? cur_tp3_price : tp_targets_count == 2 ? cur_tp2_price : cur_tp1_price
        float profit_top = math.max(cur_entry_price, max_tp)
        float profit_bot = math.min(cur_entry_price, max_tp)
        float risk_top   = math.max(cur_entry_price, cur_sl_price)
        float risk_bot   = math.min(cur_entry_price, cur_sl_price)
        box_profit := box.new(active_start_bar, profit_top, bar_end, profit_bot, border_color = color.new(C_AQUA_MINT, 65), bgcolor = color.new(C_AQUA_MINT, 90))
        box_risk   := box.new(active_start_bar, risk_top,   bar_end, risk_bot,   border_color = color.new(C_CORAL_VIBRANT, 65), bgcolor = color.new(C_CORAL_VIBRANT, 90))

// Detect Trade Lifecycle: Freeze Drawings if SL or Final TP Hit
if show_tpsl and active_trade_dir != 0 and not trade_closed and bar_index > active_start_bar
    float target_final = tp_targets_count == 3 ? cur_tp3_price : tp_targets_count == 2 ? cur_tp2_price : cur_tp1_price
    bool hit_sl_now    = (active_trade_dir == 1 and low <= cur_sl_price) or (active_trade_dir == -1 and high >= cur_sl_price)
    bool hit_final_now = (active_trade_dir == 1 and high >= target_final) or (active_trade_dir == -1 and low <= target_final)

    if hit_sl_now or hit_final_now
        trade_closed := true
        int freeze_bar = bar_index
        line.set_x2(line_entry, freeze_bar)
        label.set_x(lbl_entry, freeze_bar)
        line.set_x2(line_sl, freeze_bar)
        label.set_x(lbl_sl, freeze_bar)
        if tp_targets_count >= 1
            line.set_x2(line_tp1, freeze_bar)
            label.set_x(lbl_tp1, freeze_bar)
        if tp_targets_count >= 2
            line.set_x2(line_tp2, freeze_bar)
            label.set_x(lbl_tp2, freeze_bar)
        if tp_targets_count >= 3
            line.set_x2(line_tp3, freeze_bar)
            label.set_x(lbl_tp3, freeze_bar)
        if render_rr_boxes
            box.set_right(box_profit, freeze_bar)
            box.set_right(box_risk, freeze_bar)

// Dynamically extend active trade drawings into the right pane if trade is live
if show_tpsl and active_trade_dir != 0 and not trade_closed and barstate.islast and bar_index > active_start_bar
    int new_end = bar_index + 14
    line.set_x2(line_entry, new_end)
    label.set_x(lbl_entry, new_end)
    line.set_x2(line_sl, new_end)
    label.set_x(lbl_sl, new_end)
    if tp_targets_count >= 1
        line.set_x2(line_tp1, new_end)
        label.set_x(lbl_tp1, new_end)
    if tp_targets_count >= 2
        line.set_x2(line_tp2, new_end)
        label.set_x(lbl_tp2, new_end)
    if tp_targets_count >= 3
        line.set_x2(line_tp3, new_end)
        label.set_x(lbl_tp3, new_end)
    if render_rr_boxes
        box.set_right(box_profit, new_end)
        box.set_right(box_risk, new_end)

// Export Plots for Alerts & TradingView Data Window (Hidden from Status Line)
plot(cur_entry_price, "Export: Entry Level", color = color.white, display = display.data_window)
plot(cur_sl_price,    "Export: Stop Loss",   color = color.red,   display = display.data_window)
plot(cur_tp1_price,   "Export: TP 1 Level",  color = color.green, display = display.data_window)
plot(cur_tp2_price,   "Export: TP 2 Level",  color = color.green, display = display.data_window)
plot(cur_tp3_price,   "Export: TP 3 Level",  color = color.green, display = display.data_window)

// Target Hit Event Detection
bool tp1_hit = false
bool tp2_hit = false
bool tp3_hit = false
bool sl_hit  = false

if show_tpsl and active_trade_dir == 1
    tp1_hit := high >= cur_tp1_price and high[1] < cur_tp1_price
    tp2_hit := high >= cur_tp2_price and high[1] < cur_tp2_price
    tp3_hit := high >= cur_tp3_price and high[1] < cur_tp3_price
    sl_hit  := low  <= cur_sl_price  and low[1]  > cur_sl_price
else if show_tpsl and active_trade_dir == -1
    tp1_hit := low  <= cur_tp1_price and low[1]  > cur_tp1_price
    tp2_hit := low  <= cur_tp2_price and low[1]  > cur_tp2_price
    tp3_hit := low  <= cur_tp3_price and low[1]  > cur_tp3_price
    sl_hit  := high >= cur_sl_price  and high[1] < cur_sl_price

// ============================================================================
// 7. COMPONENT STATUS DASHBOARD TABLE (COMPACT SLEEK MATRIX)
// ============================================================================

// Duration Tracking Global States for each component
// 1. Smart Signals
var int dur_signals  = 0
var int sw_signals   = 0
var int sum_signals  = 0
var int prev_signals = 0
if core_engine_dir != prev_signals
    sw_signals += 1
    sum_signals += dur_signals
    dur_signals := 1
    prev_signals := core_engine_dir
else
    dur_signals += 1
float avg_signals = sw_signals > 0 ? (float(sum_signals) / float(sw_signals)) : float(dur_signals)

// 2. Fair Value Trail
var int dur_fvt  = 0
var int sw_fvt   = 0
var int sum_fvt  = 0
var int prev_fvt = 0
if fvt_dir != prev_fvt
    sw_fvt += 1
    sum_fvt += dur_fvt
    dur_fvt := 1
    prev_fvt := fvt_dir
else
    dur_fvt += 1
float avg_fvt = sw_fvt > 0 ? (float(sum_fvt) / float(sw_fvt)) : float(dur_fvt)

// 3. Trend Spine
var int dur_spine  = 0
var int sw_spine   = 0
var int sum_spine  = 0
var int prev_spine = 0
if spine_dir != prev_spine
    sw_spine += 1
    sum_spine += dur_spine
    dur_spine := 1
    prev_spine := spine_dir
else
    dur_spine += 1
float avg_spine = sw_spine > 0 ? (float(sum_spine) / float(sw_spine)) : float(dur_spine)

// 4. Trend Bias
var int dur_bias  = 0
var int sw_bias   = 0
var int sum_bias  = 0
var int prev_bias = 0
if bias_dir != prev_bias
    sw_bias += 1
    sum_bias += dur_bias
    dur_bias := 1
    prev_bias := bias_dir
else
    dur_bias += 1
float avg_bias = sw_bias > 0 ? (float(sum_bias) / float(sw_bias)) : float(dur_bias)

// 5. Firmament Clouds
var int dur_clouds  = 0
var int sw_clouds   = 0
var int sum_clouds  = 0
var int prev_clouds = 0
if cloud_status != prev_clouds
    sw_clouds += 1
    sum_clouds += dur_clouds
    dur_clouds := 1
    prev_clouds := cloud_status
else
    dur_clouds += 1
float avg_clouds = sw_clouds > 0 ? (float(sum_clouds) / float(sw_clouds)) : float(dur_clouds)

// 6. Trend-Range Classifier
var int dur_trc  = 0
var int sw_trc   = 0
var int sum_trc  = 0
var int prev_trc = 0
if trc_state != prev_trc
    sw_trc += 1
    sum_trc += dur_trc
    dur_trc := 1
    prev_trc := trc_state
else
    dur_trc += 1
float avg_trc = sw_trc > 0 ? (float(sum_trc) / float(sw_trc)) : float(dur_trc)

// Helper to Populate Dashboard Table Rows with High-End Styling
f_set_table_row(table t, int row, string name, bool is_enabled, int state, float avg_d, int cur_d, string icon_mode, string sz_str) =>
    color c_row_bg = row % 2 == 0 ? #0d121f : #131b2e
    string icon_str = "OFF"
    color icon_col  = #1e293b
    string str_avg  = "—"
    string str_cur  = "—"

    if is_enabled
        str_avg := str.tostring(avg_d, "#.#")
        str_cur := str.tostring(cur_d)

        if icon_mode == "Arrow"
            icon_str := state == 1 ? "▲ LONG" : state == -1 ? "▼ SHORT" : "— FLAT"
            icon_col := state == 1 ? #059669 : state == -1 ? #dc2626 : #334155
        else if icon_mode == "Range"
            icon_str := state == 0 ? "⚖ SQUEEZE" : state == 1 ? "▲ EXPANSION" : "▼ BREAKOUT"
            icon_col := state == 0 ? #475569 : state == 1 ? #059669 : #dc2626
        else if icon_mode == "Cloud"
            icon_str := state == 1 ? "🟢 DEMAND" : state == -1 ? "🔴 SUPPLY" : "— MIDWAY"
            icon_col := state == 1 ? #059669 : state == -1 ? #dc2626 : #334155

    table.cell(t, 0, row, name,     bgcolor = c_row_bg, text_color = #f8fafc, text_size = sz_str)
    table.cell(t, 1, row, icon_str, bgcolor = icon_col,  text_color = C_WHITE_CLEAN, text_size = sz_str)
    table.cell(t, 2, row, str_avg,  bgcolor = c_row_bg, text_color = #94a3b8, text_size = sz_str)
    table.cell(t, 3, row, str_cur,  bgcolor = c_row_bg, text_color = #38bdf8, text_size = sz_str)

// Instantiate Table
string table_pos_mode = table_position_in == "Bottom Right" ? position.bottom_right : table_position_in == "Bottom Left" ? position.bottom_left : table_position_in == "Top Left" ? position.top_left : position.top_right
string table_sz_mode  = table_size_in == "Tiny" ? size.tiny : table_size_in == "Normal" ? size.normal : table_size_in == "Large" ? size.large : size.small

var table dash_table = table.new(table_pos_mode, 4, 8, bgcolor = #090d16, border_color = #1e293b, border_width = 1)

if show_dashboard and barstate.islast
    color c_hdr_bg = #070a10
    table.cell(dash_table, 0, 0, "TACTICAL ENGINE",     bgcolor = c_hdr_bg, text_color = #38bdf8, text_size = table_sz_mode)
    table.cell(dash_table, 1, 0, "ORDER FLOW",          bgcolor = c_hdr_bg, text_color = #38bdf8, text_size = table_sz_mode)
    table.cell(dash_table, 2, 0, "HISTORICAL MEAN",     bgcolor = c_hdr_bg, text_color = #94a3b8, text_size = table_sz_mode)
    table.cell(dash_table, 3, 0, "LIVE BARS",           bgcolor = c_hdr_bg, text_color = #94a3b8, text_size = table_sz_mode)

    f_set_table_row(dash_table, 1, "🎯 Apex Execution Pulse",    show_signals, core_engine_dir, avg_signals, dur_signals, "Arrow", table_sz_mode)
    f_set_table_row(dash_table, 2, "🌐 Liquidity Anchor Flow",   show_fvt,     fvt_dir,         avg_fvt,     dur_fvt,     "Arrow", table_sz_mode)
    f_set_table_row(dash_table, 3, "🏛 Macro Structural Pillar",  show_spine,   spine_dir,       avg_spine,   dur_spine,   "Arrow", table_sz_mode)
    f_set_table_row(dash_table, 4, "🚀 Velocity Thrust Vector",  show_bias,    bias_dir,        avg_bias,    dur_bias,    "Arrow", table_sz_mode)
    f_set_table_row(dash_table, 5, "🛡 Volatility Armor Channel", show_clouds,  cloud_status,    avg_clouds,  dur_clouds,  "Cloud", table_sz_mode)
    f_set_table_row(dash_table, 6, "🤖 Neural Phase Detector",   show_trc,     trc_state,       avg_trc,     dur_trc,     "Range", table_sz_mode)

    // Real-Time Institutional Synergy Score Row
    int bull_cnt = (show_signals and core_engine_dir == 1 ? 1 : 0) + (show_fvt and fvt_dir == 1 ? 1 : 0) + (show_spine and spine_dir == 1 ? 1 : 0) + (show_bias and bias_dir == 1 ? 1 : 0) + (show_clouds and cloud_status == 1 ? 1 : 0) + (show_trc and trc_state == 1 ? 1 : 0)
    int bear_cnt = (show_signals and core_engine_dir == -1 ? 1 : 0) + (show_fvt and fvt_dir == -1 ? 1 : 0) + (show_spine and spine_dir == -1 ? 1 : 0) + (show_bias and bias_dir == -1 ? 1 : 0) + (show_clouds and cloud_status == -1 ? 1 : 0) + (show_trc and trc_state == -1 ? 1 : 0)
    int total_mods = (show_signals ? 1 : 0) + (show_fvt ? 1 : 0) + (show_spine ? 1 : 0) + (show_bias ? 1 : 0) + (show_clouds ? 1 : 0) + (show_trc ? 1 : 0)
    total_mods := math.max(total_mods, 1)

    string conf_str   = "SIDEWAYS"
    color  conf_col   = #475569
    string rating_str = "STAND ASIDE"
    float  conf_power = 50.0

    if bull_cnt > bear_cnt
        conf_power := (float(bull_cnt) / float(total_mods)) * 100.0
        conf_str   := bull_cnt >= 4 ? "MAX LONG" : "LONG LEAN"
        conf_col   := bull_cnt >= 4 ? #047857 : #059669
        rating_str := bull_cnt >= 4 ? "PRIME SETUP" : "MODERATE"
    else if bear_cnt > bull_cnt
        conf_power := (float(bear_cnt) / float(total_mods)) * 100.0
        conf_str   := bear_cnt >= 4 ? "MAX SHORT" : "SHORT LEAN"
        conf_col   := bear_cnt >= 4 ? #b91c1c : #dc2626
        rating_str := bear_cnt >= 4 ? "PRIME SETUP" : "MODERATE"
    else
        conf_power := 50.0
        conf_str   := "SIDEWAYS CHOP"
        conf_col   := #334155
        rating_str := "WAIT / NO LEAN"

    color c_sum_bg = #080c14
    table.cell(dash_table, 0, 7, "💎 SYSTEM SYNERGY",  bgcolor = c_sum_bg, text_color = #38bdf8, text_size = table_sz_mode)
    table.cell(dash_table, 1, 7, conf_str,             bgcolor = conf_col,  text_color = C_WHITE_CLEAN, text_size = table_sz_mode)
    table.cell(dash_table, 2, 7, str.tostring(conf_power, "#") + "% FORCE", bgcolor = c_sum_bg, text_color = #38bdf8, text_size = table_sz_mode)
    table.cell(dash_table, 3, 7, rating_str,          bgcolor = c_sum_bg, text_color = #f1f5f9, text_size = table_sz_mode)

// ============================================================================
// 8. MULTI-STEP CONFLUENCE ALERT LOGIC
// ============================================================================

// Confluence agreement checks
bool conf_trc_ok     = not alert_req_trc   or trc_is_trending
bool conf_fvt_buy    = not alert_req_fvt   or fvt_dir == 1
bool conf_fvt_sell   = not alert_req_fvt   or fvt_dir == -1
bool conf_spine_buy  = not alert_req_spine or spine_dir == 1
bool conf_spine_sell = not alert_req_spine or spine_dir == -1
bool conf_bias_buy   = not alert_req_bias  or bias_dir == 1
bool conf_bias_sell  = not alert_req_bias  or bias_dir == -1

bool multi_confluence_bull = conf_trc_ok and conf_fvt_buy and conf_spine_buy and conf_bias_buy
bool multi_confluence_bear = conf_trc_ok and conf_fvt_sell and conf_spine_sell and conf_bias_sell

// Filtered Alert Triggers
bool alert_fire_bull = false
bool alert_fire_bear = false

if alert_trigger_filter == "All Signals"
    alert_fire_bull := raw_bull_signal and multi_confluence_bull
    alert_fire_bear := raw_bear_signal and multi_confluence_bear
else if alert_trigger_filter == "Strong Signals Only"
    alert_fire_bull := is_strong_bull and multi_confluence_bull
    alert_fire_bear := is_strong_bear and multi_confluence_bear
else if alert_trigger_filter == "Normal Signals Only"
    alert_fire_bull := is_normal_bull and multi_confluence_bull
    alert_fire_bear := is_normal_bear and multi_confluence_bear
else if alert_trigger_filter == "Optimal Entries Only"
    alert_fire_bull := fire_opt_bull and multi_confluence_bull
    alert_fire_bear := fire_opt_bear and multi_confluence_bear
else if alert_trigger_filter == "Exit Signals Only"
    alert_fire_bull := exit_short
    alert_fire_bear := exit_long

// Global Alert Handler on Confirmed Bars
if barstate.isconfirmed
    if alert_fire_bull
        alert("AlgoChief Bullish Alert Triggered on " + syminfo.ticker + " | Price: " + str.tostring(close, format.mintick), alert.freq_once_per_bar_close)
    if alert_fire_bear
        alert("AlgoChief Bearish Alert Triggered on " + syminfo.ticker + " | Price: " + str.tostring(close, format.mintick), alert.freq_once_per_bar_close)

// TradingView Native Alert Conditions
alertcondition(raw_bull_signal, "Any Bullish Signal", "AlgoChief: Bullish Signal Detected on {{ticker}}")
alertcondition(raw_bear_signal, "Any Bearish Signal", "AlgoChief: Bearish Signal Detected on {{ticker}}")
alertcondition(is_strong_bull,  "Strong Bullish Signal (+▲)", "AlgoChief: Strong Bullish Signal Detected on {{ticker}}")
alertcondition(is_strong_bear,  "Strong Bearish Signal (+▼)", "AlgoChief: Strong Bearish Signal Detected on {{ticker}}")
alertcondition(fire_opt_bull,   "Optimal Entry Pullback Buy", "AlgoChief: Optimal Bullish Retest Entry on {{ticker}}")
alertcondition(fire_opt_bear,   "Optimal Entry Pullback Sell", "AlgoChief: Optimal Bearish Retest Entry on {{ticker}}")
alertcondition(fire_exit,       "Momentum Exit Signal (✕)", "AlgoChief: Momentum Take-Profit / Exit on {{ticker}}")
alertcondition(tp1_hit,         "Take Profit 1 Reached", "AlgoChief: TP1 Hit on {{ticker}}")
alertcondition(tp2_hit,         "Take Profit 2 Reached", "AlgoChief: TP2 Hit on {{ticker}}")
alertcondition(tp3_hit,         "Take Profit 3 Reached", "AlgoChief: TP3 Hit on {{ticker}}")
alertcondition(sl_hit,          "Stop Loss Reached", "AlgoChief: Stop Loss Hit on {{ticker}}")
alertcondition(alert_fire_bull, "Multi-Step Confluence Buy", "AlgoChief: High-Probability Multi-Step Bullish Setup on {{ticker}}")
alertcondition(alert_fire_bear, "Multi-Step Confluence Sell", "AlgoChief: High-Probability Multi-Step Bearish Setup on {{ticker}}")
